﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.PlcModel;
using DeHeng_Mes.Model.PlcModel.door_01;
using DeHeng_Mes.Model.Singleton;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using SqlSugar;
using System.Web;
using MappingTable = DeHeng_Mes.Utils.MappingTable;
using DeHeng_Mes.Model.OrderSingleton;
using System.Threading.Tasks;

namespace DeHeng_Mes.Dao
{
    public class OrderDao
    {

        #region
        List<PlcOrderConfigModel> readPlcList = PlcOrderConfigModelList.ReadPlcList;
        #endregion

        /// <summary>
        /// 获取订单状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool GetOrderStatus(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>()
                      .Where(x => x.OrderId == orderId)
                      .Any();
            }
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public OrderStatus GetOrder(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>()
                    .Where(x => x.OrderId == orderId)
                    .First(); // 返回单个实体
            }
        }


        /// <summary>
        /// 插入新订单信息
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        public int InsertOrder(OrderStatus orderStatus)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(orderStatus)
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 完成订单修改对应信息
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        public void UpdateOrder(string wo_code, string wo_status)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<OrderStatus>()
                  .SetColumns(x => x.EndTime == DateTime.Now)
                  .SetColumns(x => x.Status == wo_status)
                  .Where(x => x.OrderId == wo_code)
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 查找数据库是否包含该订单号的数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool OrderIsSave(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>()
                    .Where(x => x.OrderId == orderId)
                    .Any();
            }
        }

        /// <summary>
        /// 关联工单号与追溯码
        /// </summary>
        /// <param name="code"></param>
        public void InsertOrderAndTraceId(string code, string orderId)
        {
            var orderTrace = new OrderTrace()
            {
                OrderId = orderId,
                TraceId = code,
            };

            using (var db = SqlSugarConfig.Db)
            {
                Tools.ProduceLogText($"工单：{orderId}成功关联一条追溯码，追溯码为{code}");
                db.Insertable(orderTrace).AS($"order_trace{HashUtils.GetHashAsInt(orderId, 10)}").ExecuteCommand();
            }
        }

        /// <summary>
        /// 判断关联数据是否存在
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool TraceIsSave(string code, string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>()
                         .AS($"order_trace{HashUtils.GetHashAsInt(orderId, 10)}")
                         .Where(x => x.TraceId == code && x.OrderId == orderId)
                         .Any();
            }
        }

        /// <summary>
        /// 保存点焊数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <param name="errorCode"></param>
        /// <param name="num"></param>
        /// <param name="reHotTime"></param>
        /// <param name="reHotA"></param>
        /// <param name="reHotV"></param>
        /// <param name="weldTime"></param>
        /// <param name="weldA"></param>
        /// <param name="weldV"></param>
        /// <param name="r"></param>
        /// <param name="statusNo"></param>
        /// <param name="result"></param>
        public void SaveWeldSpot(TraceSpotWeld traceSpotWeld)
        {

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceSpotWeld).AS($"trace_spotweld{HashUtils.GetHashAsInt(traceSpotWeld.TraceId, 10)}").ExecuteCommand();

                Tools.ProduceLogText($"成功保存一条{traceSpotWeld.Station}工位点焊数据，关联追溯码为{traceSpotWeld.TraceId}");
            }
        }

        /// <summary>
        /// 判断点焊数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool SpotWeldIsSave(TraceSpotWeld traceSpotWeld)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceSpotWeld>()
                    .AS($"trace_spotweld{HashUtils.GetHashAsInt(traceSpotWeld.TraceId, 10)}")
                    .Where(x => x.TraceId == traceSpotWeld.TraceId && x.Station == traceSpotWeld.Station && x.Num == traceSpotWeld.Num)
                    .Any();
            }
        }

        /// <summary>
        /// 判断涂胶数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool GlueDataIsSave(string code, string station, string rangeNo)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceGlue>()
                    .AS($"trace_glue{HashUtils.GetHashAsInt(code, 10)}")
                    .Where(x => x.TraceId == code && x.Station == station && x.RangeNo == rangeNo)
                    .Any();
            }
        }

        /// <summary>
        /// 存储涂胶数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <param name="rangeNo"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="press"></param>
        /// <param name="speed"></param>
        /// <param name="amount"></param>
        /// <param name="temperature"></param>
        public void GlueDataSave(TraceGlue traceGlue)
        {

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceGlue).AS($"trace_glue{HashUtils.GetHashAsInt(traceGlue.TraceId, 10)}").ExecuteCommand();

                Tools.ProduceLogText($"成功保存一条{traceGlue.Station}工位涂胶数据，胶段号为{traceGlue.RangeNo}，关联追溯码为{traceGlue.TraceId}");
            }
        }

        /// <summary>
        /// 判断打刻数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool PointDataIsSave(string code, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TracePoint>()
                    .AS($"trace_point{HashUtils.GetHashAsInt(code, 10)}")
                    .Where(x => x.Code == code && x.Station == station)
                    .Any();
            }
        }

        /// <summary>
        /// 保存打刻数据
        /// </summary>
        /// <param name="pointData"></param>
        public void PointDataSave(PointData pointData)
        {
            var tracePoint = new TracePoint()
            {
                Code = pointData.Code,
                Station = pointData.Station,
                PointCode = pointData.PointCode,
            };

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(tracePoint).AS($"trace_point{HashUtils.GetHashAsInt(pointData.Code, 10)}").ExecuteCommand();

                Tools.ProduceLogText($"成功保存一条{pointData.Station}工位打刻数据，关联追溯码为{pointData.Code}");
            }
        }

        /// <summary>
        /// 判断涂胶视觉数据是否插入
        /// </summary>
        /// <param name="vinCode"></param>
        /// <param name="rb"></param>
        /// <returns></returns>
        public bool GlueVisionIsSave(string vinCode, string rb, string glueId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceGlueVision>()
                    .AS($"trace_glue_vision{HashUtils.GetHashAsInt(vinCode, 10)}")
                    .Where(x => x.TraceId == vinCode && x.RobotId == rb && x.GlueId == glueId)
                    .Any();
            }
        }

        /// <summary>
        /// 插入涂胶视觉数据
        /// </summary>
        /// <param name="traceGlueVision"></param>
        internal bool SaveGlueVision(TraceGlueVision traceGlueVision)
        {
            using (var db = SqlSugarConfig.Db)
            {
                int v = db.Insertable(traceGlueVision).AS($"trace_glue_vision{HashUtils.GetHashAsInt(traceGlueVision.TraceId, 10)}").ExecuteCommand();
                return v > 0;
            }
        }

        /// <summary>
        /// 判断当前测点是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pointName"></param>
        /// <returns></returns>
        public bool CCDDataIsSave(string code, string pointName)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceCCD>()
                    .AS($"trace_ccd{HashUtils.GetHashAsInt(code, 10)}")
                    .Where(x => x.TraceId == code && x.PointName == pointName)
                    .Any();
            }
        }

        /// <summary>
        /// 存储CCD测点数据
        /// </summary>
        /// <param name="traceCCD"></param>
        public void SaveCCDData(TraceCCD traceCCD)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceCCD)
                    .AS($"trace_ccd{HashUtils.GetHashAsInt(traceCCD.TraceId, 10)}")
                    .ExecuteCommand();
            }
        }

        /// <summary>
        /// 检查是否保存该路径数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool PathIsSave(string code, string path)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<DataPath>()
                    .Where(x => x.TraceId == code && x.Path == path)
                    .Any();
            }
        }

        /// <summary>
        /// 存储文件路径数据
        /// </summary>
        /// <param name="dataPath"></param>
        public void PathSave(DataPath dataPath)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(dataPath)
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 判断拉铆数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pointCount"></param>
        /// <returns></returns>
        public bool RiveteDataIsSave(string code, string pointCount, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceRivete>()
                    .Where(x => x.TraceId == code && x.PointNo == pointCount && x.Station == station)
                    .AS($"trace_rivete{HashUtils.GetHashAsInt(code, 10)}")
                    .Any();
            }
        }

        /// <summary>
        /// 存储拉铆数据
        /// </summary>
        /// <param name="traceRivete"></param>
        public void SaveRiveteData(TraceRivete traceRivete)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceRivete)
                  .AS($"trace_rivete{HashUtils.GetHashAsInt(traceRivete.TraceId, 10)}")
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据二维码获取主键
        /// </summary>
        /// <param name="code">二维码</param>
        /// <returns>二维码对应的主键</returns>
        public int GetCodeId(string code)
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                    var result = db.Queryable<TraceCode>()
                                   .Where(x => x.TraceId == code)
                                   .Select(x => x.Id)
                                   .First();

                    return result;
                }
            }
            catch (InvalidOperationException)
            {
                return 0;  // 自定义的错误值
            }
        }

        /// <summary>
        /// 获取过程数据主键集合
        /// </summary>
        /// <param name="id"></param>
        public bool GetProcessId(int id, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<CodeProcess>()
                         .Any(x => x.TraceId == id && x.Station == station);
            }
        }

        /// <summary>
        /// 追溯码是否保存
        /// </summary>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public int CodeIsSave(string traceCode, string station)
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                    var result = db.Queryable<TraceCode>()
                                   .Where(x => x.TraceId == traceCode)
                                   .Select(x => x.Id)
                                   .First();

                    if (result == 0)
                    {
                        // 若无数据，插入数据并且返回
                        TraceCode code = new TraceCode()
                        {
                            TraceId = traceCode,
                            CreateTime = DateTime.Now,
                        };

                        if (station.Equals(SystemConstant.OP10L) || station.Equals(SystemConstant.OP10R))
                        {
                            List<OrderSingletonModel> orderModel = OrderSingleton.Instance;

                            string materialId = station.EndsWith("L") ? "B04055698600" : "A04055698600";

                            foreach (var item in orderModel)
                            {
                                if (item.MaterialId.Equals(materialId))
                                {
                                    if (string.IsNullOrEmpty(item.Batch))
                                        continue;

                                    code.Batch = item.Batch;
                                }
                            }
                        }

                        Tools.ProduceLogText($"精追表新增数据，[{traceCode}]");

                        return db.Insertable(code).ExecuteReturnIdentity();
                    }
                    else
                    {
                        return result;
                    }
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"插入精追码失败，原因是{e.Message}");

                return 0;
            }
        }

        /// <summary>
        /// 批次码是否保存
        /// </summary>
        /// <param name="batchCode"></param>
        /// <returns></returns>
        public int BatchCodeIsSave(string batchCode)
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                    var result = db.Queryable<TraceBatchCode>()
                                   .Where(x => x.BatchId == batchCode)
                                   .Select(x => x.Id)
                                   .First();

                    if (result == 0)
                    {
                        // 若无数据，插入数据并且返回
                        TraceBatchCode code = new TraceBatchCode()
                        {
                            BatchId = batchCode,
                        };
                        Tools.ProduceLogText($"批追表新增数据，[{batchCode}]");

                        return db.Insertable(code).ExecuteReturnIdentity();
                    }
                    else
                    {
                        return result;
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // 若无数据，插入数据并且返回
                TraceBatchCode code = new TraceBatchCode()
                {
                    BatchId = batchCode,
                };

                using (var db = SqlSugarConfig.Db)
                {
                    var result = db.Insertable(code)
                                   .ExecuteReturnIdentity();

                    Tools.ProduceLogText($"批追表新增数据，{batchCode}");

                    return result;
                }
            }
        }

        /// <summary>
        /// 是否存储关联表数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="batchId"></param>
        /// <param name="value"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void CodeAndBatchCodeIsSave(int id, int batchId, int value, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                bool isSave = db.Queryable<CodeBatchCode>()
                                .Any(x => x.TraceId == id && x.BatchId == batchId && x.BatchCount == value && x.Station == station);

                if (!isSave)
                {
                    CodeBatchCode codeBatchCode = new CodeBatchCode()
                    {
                        TraceId = id,
                        BatchId = batchId,
                        BatchCount = value,
                        Station = station
                    };

                    int count = db.Insertable(codeBatchCode).ExecuteCommand();

                    if (count > 0)
                        Tools.ProduceLogText($"{station}插入一条关联码数据，批次投料底数为{value}");
                }
            }
        }

        /// <summary>
        /// 插入过程数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public int InsertProcessData(StationData data, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                DateTime startTime = data.StartTime ?? DateTime.MinValue;

                DateTime endTime = data.EndTime ?? DateTime.MinValue;

                int id = db.Queryable<PartProcess>()
                    .Where(x => x.Station == station
                        && x.StartTime == startTime
                        && x.EndTime == endTime)
                    .Select(x => x.Id)
                    .First();

                if (id == 0)
                {
                    string ISOK = data.Result.ToString().Equals("1") ? "OK" : "NG";

                    string operationId = MappingTable.GetOperationId(station);

                    var partProcess = new PartProcess()
                    {
                        Station = station,
                        Operation = operationId,
                        Batch = data.Batch,
                        Beat = data.Beat.ToString(),
                        RBNo = data.RBNo,
                        Type = data.Type,
                        Worker = data.Worker,
                        StartTime = startTime,
                        EndTime = endTime,
                        Result = ISOK,
                        IsSave = "0"
                    };

                    Tools.ProduceLogText($"过站信息数据采集成功，节拍为[{data.Beat}]，工站为[{data.Station}]，车型为[{data.Type}]，下挂工序为[{operationId}]，工艺结果[{ISOK}]");

                    return db.Insertable(partProcess).ExecuteReturnIdentity();
                }
                else
                {
                    return id;
                }
            }
        }

        /// <summary>
        /// 过点数据信息关联
        /// </summary>
        /// <param name="traceId"></param>
        /// <param name="processId"></param>
        /// <param name="station"></param>
        public bool ProCessIdSave(int traceId, int processId, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                bool isSave = db.Queryable<CodeProcess>()
                                .Any(x => x.TraceId == traceId && x.ProcessId == processId && x.Station == station);

                if (!isSave)
                {
                    CodeProcess codeProcess = new CodeProcess()
                    {
                        TraceId = traceId,
                        ProcessId = processId,
                        Station = station
                    };

                    int v = db.Insertable(codeProcess).ExecuteCommand();

                    Tools.ProduceLogText($"{station}关联了一条过点数据信息");

                    return v > 0;
                }

                return false;
            }
        }

        /// <summary>
        /// 查询压铆数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pointCount"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool ClinchDataIsSave(string code, string pointCount, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceRivete>()
                    .Where(x => x.TraceId == code && x.PointCount == pointCount && x.Station == station)
                    .AS($"trace_clinch{HashUtils.GetHashAsInt(code, 10)}")
                    .Any();
            }
        }

        /// <summary>
        /// 插入压铆数据
        /// </summary>
        /// <param name="traceClinch"></param>
        public void SaveClinchData(TraceClinch traceClinch)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceClinch)
                  .AS($"trace_clinch{HashUtils.GetHashAsInt(traceClinch.TraceId, 10)}")
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入看板分析数据
        /// </summary>
        /// <param name="data"></param>
        /// <param name="traceId"></param>
        /// <param name="operation"></param>
        public void InsertBoardData(StationData data, int traceId, string operation)
        {
            var boardPassRate = new BoardPassRate()
            {
                Operation = operation,
                Date = DateTime.Today,
                Time = DateTime.Now.Hour.ToString(),
                Station = data.Station,
                TraceId = traceId.ToString(),
                Result = data.Result.ToString(),
            };

            using (var db = SqlSugarConfig.Db)
            {
                bool isSave = db.Queryable<BoardPassRate>().Any(x => x.Time == boardPassRate.Time && x.Date == boardPassRate.Date && x.TraceId == boardPassRate.TraceId && x.Operation == operation && x.Station == boardPassRate.Station);

                if (!isSave)
                    db.Insertable(boardPassRate)
                      .ExecuteCommand();
            }
        }

        /// <summary>
        /// 获取当天数据
        /// </summary>
        /// <param name="date"></param>
        public List<BoardPassRate> GetWorkPartData(DateTime today)
        {
            using (var db = SqlSugarConfig.Db)
            {
                List<BoardPassRate> boardPassRates = db.Queryable<BoardPassRate>()
                                                       .Where(s => s.Date == today)
                                                       .ToList();

                return boardPassRates;
            }
        }

        /// <summary>
        /// 绑定工单与追溯码
        /// </summary>
        /// <param name="traceCode"></param>
        /// <param name="orderId"></param>
        public void BandingOrderAndTraceCode(string traceCode, string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                bool isSave = db.Queryable<OrderTrace>().Any(x => x.TraceId == traceCode && x.OrderId == orderId);

                if (!isSave)
                {
                    db.Insertable(new OrderTrace()
                    {
                        CreateTime = DateTime.Now,
                        OrderId = orderId,
                        TraceId = traceCode,
                        MaterialPushStatus = "0",
                        OperationPushStatus = "0",
                        PartPushStatus = "0",
                        StationPushStatus = "0",
                    }).ExecuteCommand();

                    Tools.ProduceLogText($"关联了一条工单与追溯码，工单为[{orderId}]，追溯码为[{traceCode}]");
                }
            }
        }

        /// <summary>
        /// 查询所有未推送的数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrderTrace>> QueryOrderTrace()
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                    List<OrderTrace> orderTraces = await db.Queryable<OrderTrace>().Where(x => x.PartPushStatus.Equals("0") || x.StationPushStatus.Equals("0")).ToListAsync();

                    return orderTraces;
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"查询未推送数据失败，原因是{ex.Message}");

                return null;
            }
        }

        /// <summary>
        /// 更新上件数据推送状态
        /// </summary>
        public async Task UpdatePartPushStatus(string orderId, string traceId)
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                   await db.Updateable<OrderTrace>()
                           .SetColumns(x => x.PartPushStatus == "1")
                           .Where(x => x.OrderId == orderId && x.TraceId == traceId)
                           .ExecuteCommandAsync();
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"更新单件推送状态失败，原因是{e.Message}");
            }
        }

        /// <summary>
        /// 获取未推送的过站信息
        /// </summary>
        /// <param name="traceId"></param>
        /// <returns></returns>
        public async Task<PartProcess> GetProcessData(int processId)
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                    PartProcess partProcess = await db.Queryable<PartProcess>()
                                                .Where(x => x.Id == processId && x.IsSave != "1")
                                                .FirstAsync();

                    return partProcess;
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"查询未推送的过站信息失败，原因是{ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 获取过站信息与二维码映射表
        /// </summary>
        /// <param name="traceId"></param>
        /// <returns></returns>
        public async Task<List<int>> GetProcessIds(int traceId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return await db.Queryable<CodeProcess>().Where(x => x.TraceId == traceId).Select(x => x.ProcessId).ToListAsync();
            }
        }

        /// <summary>
        /// 根据追溯码Id获取批次投料
        /// </summary>
        /// <param name="traceId"></param>
        /// <returns></returns>
        public async Task<List<CodeBatchCode>> GetBtachCodeList(int traceId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                List<CodeBatchCode> codeBatchCodes = await db.Queryable<CodeBatchCode>().Where(x => x.TraceId == traceId).ToListAsync();

                return codeBatchCodes;
            }
        }

        /// <summary>
        /// 根据批次码主键获取批次码
        /// </summary>
        /// <param name="batchId"></param>
        /// <returns></returns>
        public async Task<string> GetBatchCode(int batchId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                string batchCode = await db.Queryable<TraceBatchCode>().Where(x => x.Id == batchId).Select(x => x.BatchId).FirstAsync();

                return batchCode;
            }
        }

        /// <summary>
        /// 根据主键修改推送状态
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<bool> UpdateStationSaveStatus(int id)
        {
            using (var db = SqlSugarConfig.Db)
            {
                int v = await db.Updateable<PartProcess>().SetColumns(x => x.IsSave == "1").Where(x => x.Id == id).ExecuteCommandAsync();

                return v > 0;
            }
        }

        /// <summary>
        /// 根据工单与追溯码更新推送状态
        /// </summary>
        /// <param name="traceId"></param>
        /// <returns></returns>
        public async Task<bool> UpDateOrderTraceSave(string traceId, string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                int recond = await db.Updateable<OrderTrace>()
                               .SetColumns(x => x.StationPushStatus == "1")
                               .SetColumns(x => x.MaterialPushStatus == "1")
                               .Where(x => x.TraceId == traceId && x.OrderId == orderId)
                               .ExecuteCommandAsync();

                if (recond > 0)
                {
                    Tools.ProduceLogText($"单件数据推送完成，工单为[{orderId}]，单件码为[{traceId}]");
                }

                return recond > 0;
            }
        }

        /// <summary>
        /// 查找未结束的工单
        /// </summary>
        public List<OrderStatus> QueryOrder()
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>()
                         .Where(x => x.Status != "9")
                         .ToList();
            }
        }

        /// <summary>
        /// 查询是否存在下线工序
        /// </summary>
        /// <param name="processIds"></param>
        /// <returns></returns>
        public async Task<bool> GetOverStationSaveStatus(List<int> processIds)
        {
            if(processIds?.Count > 0)
            {
                foreach (var id in processIds)
                {
                    using (var db = SqlSugarConfig.Db)
                    {
                        PartProcess partProcess = await db.Queryable<PartProcess>()
                                                    .Where(x => x.Id == id)
                                                    .FirstAsync();

                        if (partProcess.Station.Equals(SystemConstant.OP180L) || partProcess.Station.Equals(SystemConstant.OP180R))
                        {
                            return partProcess.IsSave.Equals("1");
                        }
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 根据追溯码获取追溯批次
        /// </summary>
        /// <param name="traceId"></param>
        /// <returns></returns>
        public string QueryTraceBatch(string traceId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceCode>().Where(x => x.TraceId == traceId).Select(x => x.Batch).First();
            }
        }

        /// <summary>
        /// 备份扫码校验记录
        /// </summary>
        /// <param name="code"></param>
        public void BackUpCode(string code, string station)
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                    db.Insertable(new BackUpCode()
                    {
                        CreateTime = DateTime.Now,
                        TraceId = code,
                        Station = station
                    }).ExecuteCommand();
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"[{station}]校验备份失败，追溯码[{code}]，原因是{e.Message}");
            }
        }
    }
}
